﻿namespace ElencySolutions.ImageMap.Properties
{
    using System;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using EPiServer;
    using EPiServer.Core;
    using EPiServer.Web.PropertyControls;
    using EPiServer.Core.PropertySettings;

    [PropertySettings(typeof(HotSpotPropertySettings), true)]
    public class HotSpotPropertyControl : PropertyDataControl
    {
        

        #region Members

        private const string DEFAULT_IMAGE_URL_PROPERTY_NAME = "ImageUrl";
        private const string DEFAULT_IMAGE_HEIGHT_PROPERTY_NAME = "ImageHeight";
        private const string DEFAULT_IMAGE_WIDTH_PROPERTY_NAME = "ImageWidth";

        public const int DEFAULT_POPUP_WIDTH = 745;
        public const int DEFAULT_POPUP_HEIGHT = 600;

        private TextBox _infoTextBox;
        private HiddenField _xmlValue;

        #endregion Members

        #region Properties

        public string ImageUrlPropertyName
        {
            get
            {
                string propertyName = string.Empty;
                HotSpotPropertySettings settings = GetSettings();

                if (settings != null)
                    propertyName = settings.ImageUrlPropertyName;

                return string.IsNullOrEmpty(propertyName) ? DEFAULT_IMAGE_URL_PROPERTY_NAME : propertyName;
            }
        }

        public string ImageWidthPropertyName
        {
            get
            {
                string propertyName = string.Empty;
                HotSpotPropertySettings settings = GetSettings();

                if (settings != null)
                    propertyName = settings.ImageWidthPropertyName;

                return string.IsNullOrEmpty(propertyName) ? DEFAULT_IMAGE_WIDTH_PROPERTY_NAME : propertyName;
            }
        }

        public string ImageHeightPropertyName
        {
            get
            {
                string propertyName = string.Empty;
                HotSpotPropertySettings settings = GetSettings();

                if (settings != null)
                    propertyName = settings.ImageHeightPropertyName;

                return string.IsNullOrEmpty(propertyName) ? DEFAULT_IMAGE_HEIGHT_PROPERTY_NAME : propertyName;
            }
        }

        #endregion Properties


        private Control FindControlBoundToProperty(Control parent, string propertyName)
        {
            Control foundControl = null;

            foreach (Control control in parent.Controls)
            {

                if (control is IPropertyControl && ((IPropertyControl)control).PropertyData.Name == propertyName)
                {
                    foundControl = control;
                    return foundControl;
                }

                foundControl = FindControlBoundToProperty(control, propertyName);

                if (foundControl != null)
                    return foundControl;
            }

            return foundControl;
        }

        private HotSpotPropertySettings GetSettings()
        {
            if (PropertyData.SettingsContainer != null)
            {
                PropertySettingsWrapper settingsWrapper = PropertyData.SettingsContainer.GetSetting(typeof(HotSpotPropertySettings));

                if (settingsWrapper != null)
                {
                    HotSpotPropertySettings settings = settingsWrapper.PropertySettings as HotSpotPropertySettings;

                    if (settings != null)
                        return settings;
                }
            }

            return null;
        }

        /// <summary>
        /// Creates the edit controls.
        /// </summary>
        public override void CreateEditControls()
        {
            HotSpot hotSpot = GetEntityData();

            _infoTextBox = new TextBox
                               {
                                   Text = string.Format("{0}: {1}px, {2}: {3}px",
                                                     LanguageHelper.Translate("/elencySolutionsImageMap/left"),
                                                     hotSpot.Left,
                                                     LanguageHelper.Translate("/elencySolutionsImageMap/top"),
                                                     hotSpot.Top),
                                   ID = "InfoTextBox",
                                   ReadOnly = true
                               };
            Controls.Add(_infoTextBox);

            _xmlValue = new HiddenField { ID = "XmlValue", Value = hotSpot.Left + "|" + hotSpot.Top };
            Controls.Add(_xmlValue);

            Control imageUrlControl = FindControlBoundToProperty(Page, ImageUrlPropertyName);
            Control imageHeightControl = FindControlBoundToProperty(Page, ImageHeightPropertyName);
            Control imageWidthControl = FindControlBoundToProperty(Page, ImageWidthPropertyName);
            HotSpotPropertySettings settings = GetSettings();
            int popupHeight = settings != null && settings.PopupHeight.HasValue ? settings.PopupHeight.Value : DEFAULT_POPUP_HEIGHT;
            int popupWidth = settings != null && settings.PopupWidth.HasValue ? settings.PopupWidth.Value : DEFAULT_POPUP_WIDTH;

            string buttonHtml = string.Format("<input type=\"button\" class=\"epismallbutton\" value=\"...\" onclick=\"javascript:window.open('{0}?ImageUrl=' + escape(document.getElementById('{1}_ctl00').value) + '&Width=' + $($('#{2}Row').find('input')[0]).val() + '&Height=' + $($('#{3}Row').find('input')[0]).val() + '&XmlValueId={4}&id={5}&mode=hotspot&infoBoxId={6}', 'HotSpotEditor', 'menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,location=no,height={7},width={8}');\" />",
                    "/Util/ElencySolutions.ImageMapEditor.aspx",
                    imageUrlControl.ClientID,
                    imageWidthControl.ID,
                    imageHeightControl.ID,
                    _xmlValue.ClientID,
                    PageReference.StartPage.ID,
                    _infoTextBox.ClientID,
                    popupHeight,
                    popupWidth);

            Controls.Add(new Literal { Text = buttonHtml });
        }

        /// <summary>
        /// Applies edit changes
        /// </summary>
        public override void ApplyEditChanges()
        {
            HotSpot hotSpot = GetEntityData();
            string[] parts = _xmlValue.Value.Trim().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            hotSpot.Left = int.Parse(parts[0]);
            hotSpot.Top = int.Parse(parts[1]);
            string xml = ImageMapHelper.SerializeObject(hotSpot);
            SetValue(xml);
        }

        /// <summary>
        /// Gets the string value for the property
        /// </summary>
        /// <returns>Property value as a string</returns>
        private string GetRawValue()
        {
            return PropertyData.Value == null ? string.Empty : PropertyData.Value.ToString();
        }

        /// <summary>
        /// Gets the typed entity data
        /// </summary>
        /// <returns>Entity data</returns>
        private HotSpot GetEntityData()
        {
            string xml = GetRawValue();

            if (string.IsNullOrEmpty(xml))
                return new HotSpot();

            try
            {
                return ImageMapHelper.DeserializeObject<HotSpot>(xml);
            }
            catch (Exception)
            {
                return new HotSpot();
            }
        }

    }
}
